package com.laikan.reader.bookfriend.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.helpers.BasicEvent;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.DeviceUtil;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.article.activity.BookFocusDetailActivity;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.adapter.CollectAdapter;
import com.laikan.reader.core.bean.ArticelcollectBean;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.BookFocusBean;
import com.laikan.reader.core.bean.CollectBean;
import com.laikan.reader.core.events.LaiKanEvent;
import com.laikan.reader.core.utils.ActivityUitl;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.view.ProgressBar_Modern;
import com.laikan.reader.core.view.SnackBarNotice;
import com.laikan.reader.core.view.TipInfoLayout;
import com.socks.library.KLog;
import thirdparty.swipemenulistview.SwipeMenu;
import thirdparty.swipemenulistview.SwipeMenuCreator;
import thirdparty.swipemenulistview.SwipeMenuItem;
import thirdparty.swipemenulistview.SwipeMenuListView;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

/**
 * 我的收藏页面
 * Created by Administrator on 2016/10/19.
 */
public class MyCollect extends BasicActivity {

    private RelativeLayout back_layout, rl_tab, rl_title, rl_del;
    private ImageView back_tv;
    private TextView tv_edit, tv_select_all, tv_action_back, tv_buttom_del;
    private SwipeMenuListView collect_list;
    private CollectAdapter mCollectAdapter;
    private int del_num = 0; // 存放删除的数量
    private ArrayList<BookFocusBean.BookFocusDataList> deletList = new ArrayList<>(); // 待删除的列表
    private ArrayList<BookFocusBean.BookFocusDataList> collectList = new ArrayList<>();// 收藏列表
    private TipInfoLayout tipInfo; // 无网时显示的布局
    private boolean select_all = false; // 默认未全部选中
    private boolean delIsShow = false; // 默认不显示底部删除布局
    private HashSet mRankList = new HashSet();// 去重集合
    private View item_foot_view;
    private ProgressBar_Modern mProgressBarModern;
    private int mCurrentPage = 1; //当前页
    private int PAGE_LIMIT_SIZE = 10;//每页10条
    private int END_LIST_PAGE = -1; // 最后一页
    private boolean isSwip; // 判断是否侧滑删除，设置默认侧滑
    private boolean mIsRequestDataFinish = true; //默认加载完成
    private ImageView iv_book_del;
    private Drawable iv_book_del_drawable;

    @Override
    protected void assignViews() {
        setContentView(R.layout.collect_layout);
        rl_tab = (RelativeLayout)findViewById(R.id.rl_tab);
        rl_title = (RelativeLayout)findViewById(R.id.rl_title);
        rl_del = (RelativeLayout)findViewById(R.id.rl_del);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        tv_edit = (TextView)findViewById(R.id.tv_edit);
        tv_select_all = (TextView)findViewById(R.id.tv_select_all);
        tv_action_back = (TextView)findViewById(R.id.tv_action_back);
        tv_buttom_del = (TextView)findViewById(R.id.tv_buttom_del);
        collect_list = (SwipeMenuListView)findViewById(R.id.collect_list);
        iv_book_del = (ImageView)findViewById(R.id.iv_book_del);
        tipInfo = (TipInfoLayout)findViewById(R.id.tipinfo);
        mProgressBarModern = (ProgressBar_Modern)findViewById(R.id.buttom_load_progressbar);
        item_foot_view = LayoutInflater.from(this).inflate(R.layout.item_comment_foot_view, null);//脚布局
        collect_list.addFooterView(item_foot_view);
        item_foot_view.setOnClickListener(null);
    }

    @Override
    protected void initData() {
        openEventBus();
        item_foot_view.setVisibility(View.GONE);
        BitmapDrawable drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);
        iv_book_del_drawable = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(this, R.drawable.lk_book_del), Color.parseColor("#ffffff")));
        iv_book_del.setImageDrawable(iv_book_del_drawable);
        getData(true);
        mCollectAdapter = new CollectAdapter(mContext, collectList);
        collect_list.setAdapter(mCollectAdapter);

        // step 1. create a MenuCreator  第1步：设置创建器，并且在其中生成我们需要的菜单项，将其添加进菜单中
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                // create "delete" item    创建“删除”项
                // SwipeMenuItem deleteItem = new SwipeMenuItem(getApplicationContext());
                SwipeMenuItem deleteItem = new SwipeMenuItem(mContext);
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
                // set item width
                deleteItem.setWidth(dp2px(80));
                // set a icon
                // deleteItem.setIcon(R.drawable.ic_delete);
                deleteItem.setTitle(R.string.book_manager_delete_text);
                deleteItem.setTitleColor(Color.parseColor("#ffffff"));
                deleteItem.setTitleSize(17);
                // add to menu  将创建的菜单项添加进菜单中
                menu.addMenuItem(deleteItem);
            }
        };
        // set creator  为ListView设置创建器
        collect_list.setMenuCreator(creator);
    }

    @Override
    protected void setListener() {
        back_layout.setOnClickListener(this);
        tv_select_all.setOnClickListener(this);
        tv_action_back.setOnClickListener(this);
        tv_edit.setOnClickListener(this);
        rl_del.setOnClickListener(this);
        tipInfo.setOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getData(true);
            }
        });
        // set 2. listener item click event  第2步：为ListView设置菜单项点击监听器，来监听菜单项的点击事件
        collect_list.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        deletList.add(collectList.get(position));
                        isSwip = true;
                        OperationDelete();
                        break;
                }
                // true：其他已打开的列表项的菜单状态将保持原样，不会受到其他列表项的影响而自动收回
                // false:已打开的列表项的菜单将自动收回
                return false;
            }
        });

        // set SwipeListener 设置侧滑监听器，监听侧滑开始和侧滑结束
        // 注意：当我们将一个已经侧滑出来的菜单重新收回去的时候并不会调用onSwipeStart方法，但是结束的时候依然会调用onSwipeEnd方法
        collect_list.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {

            @Override
            public void onSwipeStart(int position) {
                // swipe start
            }

            @Override
            public void onSwipeEnd(int position) {
                // swipe end
            }
        });
        // set MenuStateChangeListener  设置监听Menu状态改变的监听器（Menu的打开和关闭）
        collect_list.setOnMenuStateChangeListener(new SwipeMenuListView.OnMenuStateChangeListener() {
            @Override
            public void onMenuOpen(int position) {

            }

            @Override
            public void onMenuClose(int position) {

            }
        });
        // set item click   设置列表项点击的监听器
        collect_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (rl_tab.getVisibility() == View.VISIBLE) {
                    //跳转书籍详情页TODO
                    Intent intent = new Intent(MyCollect.this, BookFocusDetailActivity.class);
                    intent.putExtra("articleId", collectList.get(i).getShorteId());
                    startActivity(intent);
                }else {
                    BookFocusBean.BookFocusDataList c = collectList.get(i);
                    if (c.isSelected()) { //已被选中
                        c.setSelected(false);
                        deletList.remove(c);
                        del_num--;
                        if (del_num == 0) {
                            tv_select_all.setText(R.string.history_select_all);
                            select_all = false;
                        }
                    }else {
                        c.setSelected(true);
                        deletList.add(c);
                        del_num++;
                        if (del_num == collectList.size()) {
                            tv_select_all.setText(R.string.cancel);
                            select_all = true;
                        }
                    }
                    mCollectAdapter.updateSelectorShow(true);
                    recordDelCollectCount(del_num);
                }
            }
        });

        collect_list.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int position) {
                if (position == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        if (!ActivityUitl.isNetworkAvailable(mContext)) {
                            SnackBarNotice.customSnackbarShow(collect_list, R.string.laikan_network_anomaly);
                        }else {
                            if (mCurrentPage != END_LIST_PAGE && mIsRequestDataFinish) {
                                getData(false);
                                tv_select_all.setText(R.string.history_select_all);
                                select_all = false;
                                mProgressBarModern.setShow();
                            }else if (mCurrentPage == END_LIST_PAGE && collectList.size() >= 10) {
                                mProgressBarModern.setHide();
                                item_foot_view.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (rl_title.getVisibility() == View.VISIBLE) {
            setProgressBarModern(12);
            OperationFinish();
            return;
        }
        //        getData(false);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    /**
     * 设置 编辑收藏列表页面加载更多显示loading的位置
     */
    private void setProgressBarModern(int dp) {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)mProgressBarModern.getLayoutParams();
        layoutParams.setMargins(0, 0, 0, dp2px(dp));
        mProgressBarModern.setLayoutParams(layoutParams);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_edit: // 编辑
                if (!delIsShow) { // 是否显示底部删除布局
                    collect_list.setSwipeDirection(0); // 禁止item滑动
                    rl_del.setVisibility(View.VISIBLE);
                    setProgressBarModern(60);
                }else {
                    rl_del.setVisibility(View.GONE);
                }
                delIsShow = !delIsShow;
                cutOverTitle(); // 切换标题
                mCollectAdapter.updateSelectorShow(true); // 是否显示单选按钮
                recordDelCollectCount(del_num); // 设置删除的数量
                break;
            case R.id.back_layout: // 返回
                finish();
                break;
            case R.id.tv_action_back: // 完成
                collect_list.setSwipeDirection(1);// 允许item滑动，默认从左向右滑动
                setProgressBarModern(12);
                OperationFinish();
                break;
            case R.id.tv_select_all: // 全选
                OperationSelectAll();
                break;
            case R.id.rl_del: // 删除
                if (deletList.size() > 0) {
                    isSwip = false;
                    OperationDelete();
                }else {
                    ToastMgr.showShortToast(R.string.no_select_collect);
                }
                break;
            default:
                break;
        }
    }

    private void getData(final boolean isShowLoadingPage) {
        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("pageNo", mCurrentPage + "");
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                mIsRequestDataFinish = false;
                if (isShowLoadingPage) {
                    tipInfo.setLoading();
                }
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                KLog.e("MyCollect :httpResponse ------- " + httpResponse.responseContent);
                Gson gson = new Gson();
                Type type = new TypeToken<BookFocusBean>() {}.getType();
                BookFocusBean result = null;
                tipInfo.setHide();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (result != null) {
                        if (null == result.getResult() || !Constants.RESULT_OK.equals(result.getResult())) {
                            ToastMgr.showShortToast(result.getError_msg());
                        }else {
                            mCollectAdapter.updateDatas(loadMoreDatas(result.getBookFocusData().getBookFocusDataList()));
                            if (result.getBookFocusData().getBookFocusDataList().size() == 0 && mCurrentPage == 1) {
                                tv_edit.setVisibility(View.GONE);
                                tipInfo.setEmptyData(R.string.no_collect_list, R.drawable.lk_no_collect);
                            }else if (result.getBookFocusData().getBookFocusDataList().size() < 10) {
                                tv_edit.setVisibility(View.VISIBLE);
                                mCurrentPage = END_LIST_PAGE;
                            }else {
                                tv_edit.setVisibility(View.VISIBLE);
                                mCurrentPage = collectList.size() / PAGE_LIMIT_SIZE + 1; //计算页数并增加
                            }
                        }
                    }else {
                        if (isShowLoadingPage) {
                            tv_edit.setVisibility(View.GONE);
                            tipInfo.setLoadError(R.string.laikan_data_load_failed);
                        }
                    }
                }catch (Exception e) {
                    if (isShowLoadingPage) {
                        tv_edit.setVisibility(View.GONE);
                        tipInfo.setLoadError(R.string.laikan_data_load_failed);
                    }
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                if (isShowLoadingPage) {
                    tv_edit.setVisibility(View.GONE);
                    tipInfo.setLoadError(R.string.laikan_network_anomaly);
                }
            }

            @Override
            public void onFinish() {
                mIsRequestDataFinish = true;
                mProgressBarModern.setHide();
            }
        };
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_collect_list);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    private ArrayList<BookFocusBean.BookFocusDataList> loadMoreDatas(ArrayList<BookFocusBean.BookFocusDataList> datas) {
        for (int i = 0; i < datas.size(); i++) {
            if (!mRankList.contains(datas.get(i).getShorteId())) {
                mRankList.add(datas.get(i).getShorteId());
                collectList.add(datas.get(i));
            }
        }
        return collectList;
    }

    /**
     * 删除操作
     */
    private void OperationDelete() {
        String delCount = "";
        StringBuilder sb = new StringBuilder();
        if (deletList.size() == 1) {
            delCount = deletList.get(0).getShorteId();
        }else {
            for (int i = 0; i < deletList.size(); i++) {
                sb.append(deletList.get(i).getShorteId() + ",");
            }
            delCount = sb.delete(sb.length() - 1, sb.length()).toString();
        }
        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("objectId", delCount);
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                BaseDataBean<CollectBean> result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<CollectBean>>() {}.getType();
                if (httpResponse == null || httpResponse.responseContent == null) {
                    return;
                }
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (result != null) {
                        if (result.getData() == null || !Constants.RESULT_OK.equals(result.getResult())) {
                            ToastMgr.showShortToast(result.getError_msg());
                        }else {
                            if (Constants.RESULT_OK.equals(result.getResult()) && result.getData().getStatus().equals("success")) {
                                ToastMgr.showShortToast(R.string.delete_success);
                                if (isSwip) {
                                    OperationDeleteManger(false);
                                }else {
                                    OperationDeleteManger(true);
                                }
                                if (collectList.size() < 10) {
                                    item_foot_view.setVisibility(View.GONE);
                                }
                                if (collectList.size() == 0) {
                                    if (rl_title.getVisibility() == View.VISIBLE) {
                                        rl_title.setVisibility(View.GONE);
                                        rl_tab.setVisibility(View.VISIBLE);
                                    }
                                    tv_edit.setVisibility(View.GONE);
                                    tipInfo.setEmptyData(R.string.no_collect_list, R.drawable.lk_no_collect);
                                }
                            }
                        }
                    }else {
                        ToastMgr.showShortToast(R.string.delete_failure);
                    }
                }catch (Exception e) {
                    ToastMgr.showShortToast(R.string.delete_failure);
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.delete_failure);
            }

            @Override
            public void onFinish() {

            }
        };
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_cancel_collect);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    @Override
    protected void parseEvent(BasicEvent event) {
        switch (event.getEventID()) {
            case LaiKanEvent.EVENT_ID_CANCLE_COLLECT:
                for (int i = 0; i < collectList.size(); i++) {
                    if (event.getEventAction().equals(collectList.get(i).getShorteId())) {
                        collectList.remove(i);
                        mCollectAdapter.updateDatas(collectList);
                    }
                }
                break;
            case LaiKanEvent.EVENT_ID_ADD_COLLECT:
                ArticelcollectBean.ArticelCollectData articelData = (ArticelcollectBean.ArticelCollectData)event.getElves();
                BookFocusBean.BookFocusDataList list = new BookFocusBean().new BookFocusDataList();
                list.setAuthor(articelData.getAuthor());
                list.setImg(articelData.getImg());
                list.setIntro(articelData.getIntro());
                list.setReadNum(articelData.getReadNum());
                list.setShorteId(String.valueOf(articelData.getShorteId()));
                list.setTitle(articelData.getTitle());
                list.setType(articelData.getType());
                collectList.add(0, list);
                mCollectAdapter.updateDatas(collectList);
                break;
            default:
                break;
        }
    }

    /**
     * 完成按钮的操作，重置数据的状态
     */
    private void OperationFinish() {
        if (rl_title.getVisibility() == View.VISIBLE) {
            delIsShow = false;
            rl_del.setVisibility(View.GONE);
            cutOverTitle();
            for (BookFocusBean.BookFocusDataList c : collectList) {
                c.setSelected(false);
            }
            deletList.clear();
            mCollectAdapter.updateSelectorShow(false);
            select_all = false;
            del_num = 0;
            recordDelCollectCount(del_num);
            tv_select_all.setText(R.string.history_select_all);
        }
    }

    private void OperationDeleteManger(boolean isShowSelectedBtn) {
        collectList.removeAll(deletList); //从收藏列表中清除存入待删除列表中的数据
        deletList.clear();
        del_num = 0;
        recordDelCollectCount(del_num);
        select_all = false;
        if (isShowSelectedBtn) {
            mCollectAdapter.updateSelectorShow(true); //更新收藏列表
        }else {
            mCollectAdapter.updateSelectorShow(false); //更新收藏列表
        }
        tv_select_all.setText(R.string.history_select_all); //重置按钮
    }

    /**
     * 全选按钮的操作
     */
    private void OperationSelectAll() {
        if (!select_all) {
            tv_select_all.setText(R.string.cancel);
            del_num = collectList.size();
            for (BookFocusBean.BookFocusDataList c : collectList) {
                c.setSelected(true);
                deletList.add(c);
            }
            select_all = true;
        }else {
            tv_select_all.setText(R.string.history_select_all);
            del_num = 0;
            for (BookFocusBean.BookFocusDataList c : collectList) {
                c.setSelected(false);
            }
            deletList.clear();
            select_all = false;
        }
        mCollectAdapter.updateSelectorShow(true);
        recordDelCollectCount(del_num);
    }

    /**
     * 切换标题
     */
    private void cutOverTitle() {
        if (rl_title.getVisibility() == View.VISIBLE) {
            rl_title.setVisibility(View.GONE);
            rl_tab.setVisibility(View.VISIBLE);
        }else {
            rl_title.setVisibility(View.VISIBLE);
            rl_tab.setVisibility(View.GONE);
        }
    }

    /**
     * 设置删除的数量
     */
    private void recordDelCollectCount(int del_num) {
        tv_buttom_del.setText(DeviceUtil.getHtmlFormatedString(mContext, R.string.book_has_selected, del_num));
    }

    private int dp2px(int dp) {
        return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }

    /**
     * 点击编辑进入页面后，按返回键的处理操作 返回收藏页面
     */
    @Override
    public void onBackPressed() {
        if (rl_title.getVisibility() == View.VISIBLE) {
            OperationFinish();
            return;
        }
        super.onBackPressed();
    }

}
